package com.tanhua.mongo.api;

import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.model.mongo.Video;
import com.tanhua.mongo.utils.IdWorker;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class VideoApiImpl implements VideoApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdWorker idWorker;

    /**
     * 保存视频数据
     *
     * @param video
     * @return
     */
    @Override
    public String saveVideo(Video video) {
        video.setVid(idWorker.getNextId("video"));
        mongoTemplate.save(video);
        return video.getId().toHexString();
    }

    /**
     * 获取redis中的视频数据
     *
     * @param vids
     * @return
     */
    @Override
    public List<Video> findRedisVids(List<Long> vids) {
        return mongoTemplate.find(Query.query(Criteria.where("vid").in(vids)),Video.class);
    }

    /**
     * 分页查询视频数据
     *
     * @param page
     * @param pagesize
     * @return
     */
    @Override
    public List<Video> findVideo(int page, int pagesize) {
        Query query = new Query().skip((page -1) * pagesize).limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));

        return mongoTemplate.find(query,Video.class);
    }
}
